package com.fyb.user.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fyb.user.entity.UserEntity;
import com.fyb.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.ConnectionHolder;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.concurrent.CompletableFuture;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private TransactionTemplate transactionTemplate;

    /**
     * 使用TransactionTemplate 手动管理事务
     */
    @Transactional
    @Override
    public void testTransactional2() {

        //主线程操作
        jdbcTemplate.execute("INSERT INTO users (email, name, password) VALUES ('1', '1', '1')");

        //获取主线程的数据库操作
        Connection connection = DataSourceUtils.getConnection(dataSource);

        try {
            CompletableFuture.runAsync( () -> {
               //将主线程的连接绑定到子线程
                TransactionSynchronizationManager.bindResource(dataSource,new ConnectionHolder(connection));
                try {
                    //子线程操作
                    jdbcTemplate.execute("INSERT INTO `user` (`name`, `phone`, `create_by`, `remark`, `balance`) VALUES ('String1', 'String1', 'String1', 'cc', 1000.00)");
//                    throw new RuntimeException("子线程异常");
                }finally {
                    //在子线程中释放连接
                    TransactionSynchronizationManager.unbindResource(dataSource);
                }
            }).get();//等待子线程完成
        }catch (Exception e){
            throw new RuntimeException("子线程异常导致事务回滚",e);
        }finally {
            //在主线程中释放连接
            DataSourceUtils.releaseConnection(connection,dataSource);
        }
    }
}
